package com.bnz.servlet;

import com.alibaba.fastjson.JSON;
import com.bnz.pojo.Classes;
import com.bnz.pojo.Student;
import com.bnz.service.ClassesService;
import com.bnz.service.StudentService;
import com.bnz.util.PageResult;
import com.bnz.util.R;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebServlet("/classes")
public class ClassesServlet extends HttpServlet {
	private ClassesService classesService;
	@Override
	public void init() throws ServletException {
		// 得到spring容器
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		// 得到容器中的bean
		classesService = wac.getBean(ClassesService.class);

	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//处理中文乱码
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=utf-8");
		//得到请求参数，根据参数调用方法
		String cmd = req.getParameter("cmd");
		if(!StringUtils.isEmpty(cmd)){
			//查询学生列表
			if("list".equals(cmd)){
				list(req,resp);
			}
		}
	}


	//列表班级
	private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//查询所有学生
		List<Classes> studentList = classesService.findAll();
		//输出到页面
		R r = R.ok().data("list", studentList);
		resp.getWriter().println(JSON.toJSONString(r));
		//刷瓣页面
		resp.getWriter().flush();
	}

}
